package com.zhanggm.product.controller;


import cn.hutool.crypto.SecureUtil;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhanggm.product.config.AjaxResult;
import com.zhanggm.product.entity.TM4Product;
import com.zhanggm.product.service.ITM4ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhanggm
 * @since 2024-05-29
 */
@RestController
@RequestMapping("/t-m4-product")
public class TM4ProductController {

    @Autowired
    ITM4ProductService itm4ProductService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    HttpServletRequest request;

    @Value("${server.port}")
    private String servverPort;


    @RequestMapping("upload")
    public AjaxResult upload(MultipartFile file) throws IOException {
        String fileName = UUID.randomUUID() + ".jpg";
        file.transferTo(new File("/home/pic/" + fileName));
        return AjaxResult.success("http://loalhsot:" + servverPort +"/"+ fileName);
    }


    @GetMapping("list")
    public Object list() {

        String token = request.getHeader("token");
        Object id = JWTUtil.parseToken(token).getPayload("id");
        if (id == null) {
            return AjaxResult.error("用户未登录");
        }
        //封装查询条件
        LambdaQueryWrapper<TM4Product> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(TM4Product::getName);
        //分页
        List<TM4Product> list = itm4ProductService.list();
        PageInfo<TM4Product> tm4ProductPageInfo = new PageInfo<>(list);
        return AjaxResult.success(tm4ProductPageInfo);
    }





    @GetMapping("getById")
    public AjaxResult getById(Integer id) {
        return AjaxResult.success(itm4ProductService.getById(id));
    }

    @GetMapping("/getListByIds")
    public List<TM4Product> getListByIds(@RequestParam Set<String> ids) {
        List<TM4Product> tm4Products = itm4ProductService.listByIds(ids);
        return tm4Products;
    }

}
